package com.study.jyg.rxjava2study;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;

import androidx.multidex.MultiDexApplication;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.study.jyg.rxjava2study.crash.CrashHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import rxhttp.HttpSender;

public class MyApplication extends MultiDexApplication {

    private static List<AppDeskTopListener> appDeskTopListeners = new ArrayList<>();//app前/后台监听
    private static int anInt = 0;

    private static MyApplication context;

    private final String UM_KEY = "5c7755adb465f59b05001182";

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        setAllActivityListener();//设置app活动监听管理
        initOkGo();//配置okgo
        initRxhttp();//初始化rxhttp

        CrashHandler.getInstance().init();//异常捕获类，捕获当前UI线程
    }

    /**
     * RxHttp 初始化
     */
    private void initRxhttp() {
        //设置debug模式，此模式下有日志打印
        HttpSender.setDebug( true);
        //非必须,只能初始化一次，第二次将抛出异常
        HttpSender.init( new OkHttpClient.Builder()
                .connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
                .writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
                .readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
                .cache(new Cache(new File(Environment.getExternalStorageDirectory()+"/httpcache"), 24*60*OkGo.DEFAULT_MILLISECONDS)).build());
    }


    /**
     * okGo网络请求配置
     *
     * @return
     */
    private void initOkGo() {
        //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
        HttpHeaders headers = new HttpHeaders();
        headers.put("commonHeaderKey1", "commonHeaderValue1");    //header不支持中文，不允许有特殊字符
        headers.put("commonHeaderKey2", "commonHeaderValue2");
        HttpParams params = new HttpParams();
        params.put("commonParamsKey1", "commonParamsValue1");     //param支持中文,直接传,不要自己编码
        params.put("commonParamsKey2", "这里支持中文参数");
        //----------------------------------------------------------------------------------------------------//

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);//log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);//决定了log在控制台显示的颜色,级别
        builder.addInterceptor(loggingInterceptor);

        //超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间

        //自动管理cookie（或者叫session的保持），以下几种任选其一就行
        //builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));            //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));              //使用数据库保持cookie，如果cookie不过期，则一直有效
        //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));            //使用内存保持cookie，app退出后，cookie消失

        //https相关设置，以下几种方案根据需要自己设置
        //方法一：信任所有证书,不安全有风险
        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
        //方法二：自定义信任规则，校验服务端证书
        //HttpsUtils.SSLParams sslParams2 = HttpsUtils.getSslSocketFactory(new SafeTrustManager());
        //方法三：使用预埋证书，校验服务端证书（自签名证书）
        //HttpsUtils.SSLParams sslParams3 = HttpsUtils.getSslSocketFactory(getAssets().open("srca.cer"));
        //方法四：使用bks证书和密码管理客户端证书（双向认证），使用预埋证书，校验服务端证书（自签名证书）
        //HttpsUtils.SSLParams sslParams4 = HttpsUtils.getSslSocketFactory(getAssets().open("xxx.bks"), "123456", getAssets().open("yyy.cer"));
        builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
        //配置https的域名匹配规则，详细看demo的初始化介绍，不需要就不要加入，使用不当会导致https握手失败
        //builder.hostnameVerifier(new SafeHostnameVerifier());

        OkGo.getInstance().init(this)
                .setOkHttpClient(builder.build())
                // okGo框架的特有设置
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3);                               //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
//                .addCommonHeaders(headers)                      //全局公共头
//                .addCommonParams(params);                       //全局公共参数
    }


    /**
     * 注册 app前后台监听
     *
     * @param listener
     */
    public static void registerAppDeskTopListener(AppDeskTopListener listener) {
        if (!appDeskTopListeners.contains(listener)) {
            appDeskTopListeners.add(listener);
        }
    }

    /**
     * 注销 app前后台监听
     *
     * @param listener
     */
    public static void unRegisterAppDeskTopListener(AppDeskTopListener listener) {
        if (appDeskTopListeners.contains(listener))
            appDeskTopListeners.remove(listener);
    }

    /**
     * google提供的管理所有actiivty的监听
     */
    private void setAllActivityListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                if (anInt == 0) {
                    for (AppDeskTopListener listener : appDeskTopListeners) {
                        listener.deskTop(true);
                    }
                }
                anInt++;
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                anInt--;
                if (anInt == 0) {
                    for (AppDeskTopListener listener : appDeskTopListeners) {
                        listener.deskTop(false);
                    }
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    public static Context getAppContext() {
        return context;
    }

    /**
     * 判断app是否在前台
     *
     * @return
     */
    public static boolean isonTop() {
        return anInt == 0;
    }


    @Override
    public void onTerminate() {
        super.onTerminate();

    }


    public interface AppDeskTopListener {
        void deskTop(boolean top);
    }
}
